package com.yylending.las.authority.gestures;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.Loader;
import android.view.View;
import android.widget.*;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.yyfax.common.CLog;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yylending.las.R;
import com.yylending.las.YJKD;
import com.yylending.las.base.BaseActivity;
import com.yylending.las.common.widgets.lockpattern.LockPatternIndicator;
import com.yylending.las.common.widgets.lockpattern.LockPatternView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by HenryZhang on 2016/11/21.
 * Copyright © 2016 www.yyfax.com. All Rights Reserved.
 */
public class ModifyGesturesActivity extends BaseActivity {
	private final static String TAG = "ModifyGesturesActivity";

	public final static int GESTURE_SET = 0;
	public final static int GESTURE_MODIFY = 1;
	public final static int GESTURE_RESET = 2;
	public final static int GESTURE_CLOSE = 3;
	public final static int GESTURE_FIRST_LOGIN = 4;
	private final static String EXTRA_BUSINESS = "extra_business";
	private final static long DELAY_TIME = 600L;

	private final static int POINT_COUNT = 4;

	@BindView(R.id.modify_indicator)
	LockPatternIndicator mIndicator;
	@BindView(R.id.modify_message)
	TextView mMessage;
	@BindView(R.id.modify_pattern_lock)
	LockPatternView mLockPattern;
	@BindView(R.id.gesture_modify_container)
	View mGestureModifyContainer;
	@BindView(R.id.gestures_reset_container)
	View mGesturesResetContainer;
	@BindView(R.id.gestures_reset_password_ic)
	ImageView mResetPasswordIc;
	@BindView(R.id.gestures_reset_password)
	EditText mResetPassword;
	@BindView(R.id.gestures_reset_delete)
	ImageView mResetDelete;
	@BindView(R.id.gestures_reset_eyes_open)
	CheckBox mEyesOpen;
	@BindView(R.id.gestures_reset_forgot)
	TextView mForgot;
	@BindView(R.id.gestures_reset_next)
	Button mNext;

	private List<LockPatternView.Cell> mChosenPattern = new ArrayList<>();
	private Status mStatus;
	//0：设置 1：修改 2：重置 3：手势验证 4：首次登陆后设置
	private int mBusiness;

	public static void start(Activity aty, int business) {
		Intent i = new Intent(aty, ModifyGesturesActivity.class);
		i.putExtra(EXTRA_BUSINESS, business);
		aty.startActivity(i);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(EXTRA_BUSINESS, mBusiness);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mBusiness = savedInstanceState.getInt(EXTRA_BUSINESS, 0);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gestures_modify);
		ButterKnife.bind(this);
		mBusiness = getIntent().getIntExtra(EXTRA_BUSINESS, 0);
		switch (mBusiness) {
			case GESTURE_SET:
				setTitle(R.string.gesture_create);
				updateStatus(Status.CREATE_GESTURE, null);
				break;
			case GESTURE_MODIFY:
				setTitle(R.string.gesture_modify);
				updateStatus(Status.VALIDATE, null);
				break;
			case GESTURE_RESET:
				setTitle(R.string.gesture_reset);
				updateStatus(Status.CREATE_GESTURE, null);
				break;
			case GESTURE_CLOSE:
				setTitle(R.string.gesture_close);
				updateStatus(Status.VALIDATE, null);
				break;
			case GESTURE_FIRST_LOGIN:
				setTitle(R.string.gesture_create);
				updateStatus(Status.CREATE_GESTURE, null);
				//setBtnRightTx(R.string.ignore_gesture_setting);
				break;
		}
		initView();
	}

	private void initView() {
		mGesturesResetContainer.setVisibility(View.GONE);
		mGestureModifyContainer.setVisibility(View.VISIBLE);
		mLockPattern.setOnPatternListener(mListener);
	}

	private LockPatternView.OnPatternListener mListener = new LockPatternView.OnPatternListener() {
		@Override
		public void onPatternStart() {
			CLog.i(TAG, "OnPatternListener onPatternStart mStatus=" + mStatus + ";mBusiness=" + mBusiness);
			mLockPattern.removePostClearPatternRunnable();
			switch (mBusiness) {
				case GESTURE_FIRST_LOGIN:
				case GESTURE_SET:
				case GESTURE_MODIFY:
				case GESTURE_RESET:
					if (mStatus.strId == Status.CONFIRM_ERROR.strId || mStatus.strId == Status.CONFIRM_LESS_ERROR.strId) {
						updateStatus(Status.CORRECT, null);
					} else if (mStatus.strId == Status.LESS_ERROR.strId) {
						updateStatus(Status.CREATE_GESTURE, null);
					}
					/*else if (mStatus.strId == Status.VALIDATE_ERROR.strId) {
						//updateStatus(Status.VALIDATE, null);
					}*/
					break;
				case GESTURE_CLOSE:
					/*if (mStatus.strId == Status.VALIDATE_ERROR.strId) {
						updateStatus(Status.VALIDATE, null);
					}*/
					break;
			}
			mLockPattern.setPattern(LockPatternView.DisplayMode.DEFAULT);
		}

		@Override
		public void onPatternComplete(List<LockPatternView.Cell> pattern) {
			CLog.i(TAG, "OnPatternListener onPatternComplete mStatus=" + mStatus + ";mBusiness=" + mBusiness);
			switch (mStatus) {
				case VALIDATE:
				case VALIDATE_ERROR:
					if (YJKD.getInstance().checkChosenPattern(pattern)) {
						CLog.i(TAG, "OnPatternListener onPatternComplete 手势验证成功=" + mStatus);
						if (mBusiness == GESTURE_CLOSE) {
							YJKD.clearGesture(false);
							finish();
							return;
						}
						updateStatus(Status.CREATE, null);
						if (mBusiness == GESTURE_MODIFY) {
							GesturesPresenter.writeStatus(false);
							YJKD.getInstance().removeChosenPattern();
						}
					} else {
						updateStatus(Status.VALIDATE_ERROR, null);
					}
					break;
				case CREATE_GESTURE:
				case CREATE:
					if (pattern.size() < POINT_COUNT) {
						updateStatus(Status.LESS_ERROR, pattern);
						break;
					}
					mChosenPattern.clear();
					mChosenPattern.addAll(pattern);
					updateStatus(Status.CORRECT, pattern);
					/*if (mBusiness == GESTURE_MODIFY || mBusiness == GESTURE_SET || mBusiness == GESTURE_RESET || mBusiness == GESTURE_FIRST_LOGIN) {
						setBtnRightTx(R.string.draw_again);
					}*/
					break;
				case CORRECT:
					if (pattern.size() < POINT_COUNT) {
						updateStatus(Status.CONFIRM_LESS_ERROR, pattern);
						break;
					}
					if (mChosenPattern.equals(pattern)) {
						GesturesPresenter.resetGestureCount();
						updateStatus(Status.CONFIRM_CORRECT, pattern);
					} else {
						updateStatus(Status.CONFIRM_ERROR, pattern);
					}
					break;
			}
		}
	};

	/**
	 * 更新状态
	 */
	protected void updateStatus(Status status, List<LockPatternView.Cell> pattern) {
		mStatus = status;
		mMessage.setTextColor(getResources().getColor(status.colorId));
		mMessage.setText(status.strId);
		switch (status) {
			case VALIDATE:
			case VALIDATE_ERROR:
				mLockPattern.setPattern(LockPatternView.DisplayMode.NORMAL);
				mLockPattern.postClearPatternRunnable(DELAY_TIME);
				break;
			case VALIDATE_RETRY_MAX:
				mLockPattern.setEnabled(false);
				break;
			case CREATE:
				mLockPattern.setPattern(LockPatternView.DisplayMode.DEFAULT);
				break;
			case CORRECT:
				updateLockPatternIndicator();
				mLockPattern.setPattern(LockPatternView.DisplayMode.DEFAULT);
				break;
			case LESS_ERROR:
				mLockPattern.setPattern(LockPatternView.DisplayMode.DEFAULT);
				break;
			case CONFIRM_LESS_ERROR:
			case CONFIRM_ERROR:
				mLockPattern.setPattern(LockPatternView.DisplayMode.ERROR);
				mLockPattern.postClearPatternRunnable(DELAY_TIME);
				break;
			case CONFIRM_CORRECT:
				if(YJKD.getInstance().saveChosenPattern(pattern)){
					CLog.i("ACache", "保存手势密码成功");
					mLockPattern.setPattern(LockPatternView.DisplayMode.DEFAULT);
					setLockPatternSuccess();
				}else{
					CLog.i("ACache", "保存手势密码失败");
					YJKD.clearGesture(false);
					showLongToast("手势密码保存失败，请重试！");
					//mLockPattern.setPattern(LockPatternView.DisplayMode.DEFAULT);
					finish();
				}
				break;
		}
	}

	private void writeStatus(boolean isChecked) {
		GesturesPresenter.writeStatus(isChecked);
	}

	protected enum Status {
		/**
		 * 验证原始手势密码
		 */
		VALIDATE(R.string.create_gesture_validate, R.color.color_333333),
//grey_a5a5a5
		VALIDATE_ERROR(R.string.gesture_retry, R.color.color_f4333c),
		VALIDATE_RETRY_MAX(R.string.create_gesture_retry_max, R.color.color_f4333c),
		/**
		 * 默认的状态，刚开始的时候（初始化状态）
		 */
		CREATE(R.string.create_gesture_default, R.color.color_333333),
//grey_a5a5a5
		/**
		 * 第一次记录成功
		 */
		CORRECT(R.string.create_gesture_correct, R.color.color_333333),
//grey_a5a5a5
		/**
		 * 连接的点数小于4
		 */
		LESS_ERROR(R.string.create_gesture_less_error, R.color.color_f4333c),
		/**
		 * 二次确认错误
		 */
		CONFIRM_ERROR(R.string.create_gesture_confirm_error, R.color.color_f4333c),
		/**
		 * 二次确认时连接的点数小于4
		 */
		CONFIRM_LESS_ERROR(R.string.confirm_gesture_less_error, R.color.color_f4333c),
		/**
		 * 二次确认正确
		 */
		CONFIRM_CORRECT(R.string.create_gesture_confirm_correct, R.color.color_333333),
//grey_a5a5a5
		CREATE_GESTURE(R.string.create_gesture_new, R.color.color_333333),
		CONFIRM_GESTURE(R.string.create_gesture_correct, R.color.color_333333);

		private int strId;
		private int colorId;

		Status(int strId, int colorId) {
			this.strId = strId;
			this.colorId = colorId;
		}
	}

	private void updateLockPatternIndicator() {
		if (mChosenPattern.size() > 0)
			mIndicator.setIndicator(mChosenPattern);
	}

	private void setLockPatternSuccess() {
		switch (mBusiness) {
			case GESTURE_SET:
			case GESTURE_FIRST_LOGIN:
				writeStatus(true);
				finish();
				break;
			case GESTURE_MODIFY:
				GesturesPresenter.writeStatus(true);
				finish();
				break;
			case GESTURE_RESET:
				GesturesPresenter.writeStatus(true);
				finish();
				break;
		}
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();// TODO: 2017/3/21 首次设置的时候判断
		finish();
	}

	@Override
	public void onBackBtnPressed() {
		super.onBackBtnPressed();
		finish();
	}

	@Override
	public void onRightBtnPressed() {
		super.onRightBtnPressed();
		switch (mBusiness) {
			case GESTURE_MODIFY:
				updateStatus(Status.CREATE, null);
				mChosenPattern.clear();
				mIndicator.setDefaultIndicator();
				break;
			case GESTURE_SET:
			case GESTURE_RESET:
				updateStatus(Status.CREATE_GESTURE, null);
				mChosenPattern.clear();
				mIndicator.setDefaultIndicator();
				break;
			case GESTURE_FIRST_LOGIN:
				/*if (getString(R.string.ignore_gesture_setting).equals(getBtnRightTx())) {
					finish();
				} else if (getString(R.string.draw_again).equals(getBtnRightTx())) {
					setBtnRightTx(R.string.ignore_gesture_setting);
					updateStatus(Status.CREATE, null);
					mChosenPattern.clear();
					mIndicator.setDefaultIndicator();
				}*/
				break;
		}
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {

	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		return null;
	}
}